package com.blb.eduuserservice.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.common.entity.ResponseResult;
import com.blb.common.entity.Student;
import com.blb.common.util.JwtUtils;
import com.blb.common.util.RsaUtils;
import com.blb.eduuserservice.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jcajce.provider.asymmetric.rsa.RSAUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功处理器
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private StudentService studentService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //获得登录成功的用户信息
        User user = (User) authentication.getPrincipal();
        //通过用户名将学员信息查询出来
        Student stu = studentService.getOne(new QueryWrapper<Student>().lambda().eq(Student::getUsername, user.getUsername()));
        //生成jwt字符串
        String token = JwtUtils.generateUserToken(stu, RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES);
        log.info("生成用户token：{}",token);
        //发送到前端
        ResponseResult.write(httpServletResponse,ResponseResult.ok(stu,token,""));
    }
}
